package leetcode;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-11-26 23:42
 **/
public class LeetCode859 {

    public boolean buddyStrings(String s, String goal) {
        if (s.length() != goal.length()) {
            return false;
        }
        int len = s.length();
        if (s.equals(goal)) {
            int[] count = new int[26];
            for (int i = 0; i < len; i++) {
                count[s.charAt(i) - 'a']++;
                if (count[s.charAt(i) - 'a'] > 1) {
                    return true;
                }
            }
            return false;
        } else {
            int first = -1;
            int second = -1;
            for (int i = 0; i < len; i++) {
                //只能有两处不一样，高于两处两个字符串必不相等。
                if (s.charAt(i) != goal.charAt(i)) {
                    if (first == -1) {
                        first = i;
                    } else if (second == -1) {
                        second = i;
                    } else {
                        return false;
                    }
                }
            }
            //当有两处不同，且s[first] == goal[second] && s[second] == goal[first]为真时才返回true
            return first != -1 && second != -1 && s.charAt(second) == goal.charAt(first) && s.charAt(first) == goal.charAt(second);
        }
    }

}
